package com.ldodds.deville.calais;

import java.text.CharacterIterator;
import java.text.MessageFormat;
import java.text.StringCharacterIterator;

import com.ldodds.deville.util.XML;

/**
 * <c:params xmlns:c=\"http://s.opencalais.com/1/pred/\" 
 * xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><c:processingDirectives c:contentType=\"text/txt\" c:outputFormat=\"xml/rdf\"></c:processingDirectives><c:userDirectives c:allowDistribution=\"true\" c:allowSearch=\"true\" c:externalID=\"17cabs901\" c:submitter=\"ABC\"></c:userDirectives><c:externalMetadata></c:externalMetadata></c:params>
 * 
 * @author Leigh Dodds
 */
public class ParametersXMLBuilderImpl implements ParametersXMLBuilder
{

	public String buildXML(Parameters parameters) {
		if (parameters == null) {
			throw new IllegalArgumentException("parameters may not be null");
		}
		StringBuffer paramsXML = new StringBuffer();
		paramsXML.append( getHeader() );
		paramsXML.append( getProcessingDirectives(parameters) );
		paramsXML.append( getUserDirectives(parameters) );
		paramsXML.append( getExternalMetadata(parameters) );
		paramsXML.append( getFooter() );
		return paramsXML.toString();
	}

	String getUserDirectives(Parameters parameters) {
		final String template = "<c:userDirectives " +
				"c:allowDistribution=\"{0}\" " +
				"c:allowSearch=\"{1}\" " +
				"c:externalID=\"{2}\" " +
				"c:submitter=\"{3}\">" +
				"</c:userDirectives>";
		
		Object[] arguments = new Object[4];
		arguments[0] = Boolean.toString( parameters.isAllowDistribution() );
		arguments[1] = Boolean.toString( parameters.isAllowSearch() );
		arguments[2] = XML.escapeXML( parameters.getExternalID() );
		arguments[3] = XML.escapeXML( parameters.getSubmitter() );
		
		return MessageFormat.format(template, arguments);
	}
	
	String getProcessingDirectives(Parameters parameters) {
		final String template = "<c:processingDirectives " +
				"c:contentType=\"{0}\" " +
				"c:outputFormat=\"{1}\">" +
				"</c:processingDirectives>";
		
		Object[] arguments = new Object[2];
		arguments[0] = parameters.getContentType();
		arguments[1] = parameters.getOutputFormat();
		
		return MessageFormat.format(template, arguments);
	}
	
	String getExternalMetadata(Parameters parameters) {
		return "<c:externalMetadata></c:externalMetadata>";
	}
	
	private String getHeader() {
		return "<c:params xmlns:c=\"http://s.opencalais.com/1/pred/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">";
	}
	
	private String getFooter() {
		return "</c:params>";
	}
	
}
